package com.gyg.controller;


import cn.hutool.core.lang.Assert;
import com.gyg.common.lang.Result;
import com.gyg.entity.Blog;
import com.gyg.service.IBlogService;
import com.gyg.shiro.AccountProfile;
import com.gyg.util.RedisUtil;
import com.gyg.util.ShiroUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * InnoDB free: 11264 kB 前端控制器
 * </p>
 *
 * @author 关注公众号：码猿编程日记
 * @since 2021-09-21
 */
@RestController
//@RequestMapping("/blog")
public class BlogController {

    @Autowired
    IBlogService blogService;

    @Autowired
    RedisUtil redisUtil;

    /**
     * 分页博客页
     *
     * @param currentPage
     * @return
     */
    @RequestMapping("/blogs")
    public Result list(Integer currentPage,Long userId) {
        //初始化关注数
        if(redisUtil.get("follow") == null) {
            redisUtil.set("follow", "" + 0);
        }
        System.out.println("userId=" + userId);
        AccountProfile accountProfile =  (AccountProfile) SecurityUtils.getSubject().getPrincipal();
        System.out.println(accountProfile);
        return Result.success(blogService.list());
    }

    /**
     * 查找指定的博客
     *
     * @param id
     * @return
     */
    @GetMapping("/blog/{id}")
    public Result detail(@PathVariable(name = "id") long id) {

        Blog blog = blogService.getOne(id);
//        用断言来来判断文章是否找不到
        Assert.notNull(blog, "该博客已经被删除！");

        //初始化点赞
        if(redisUtil.get("@"+id) == null){
            redisUtil.set("@"+id,""+0);
        }
        //初始化收藏
        if(redisUtil.get("$"+id) == null){
            redisUtil.set("$"+id,""+0);
        }
//        返回该博客数据
        return Result.success(blog);
    }

    /**
     * @param blog
     * @return
     */
//    只有登录之后才能编辑
    @RequiresAuthentication
    @PostMapping("/blog/edit")
    public Result edit(@Validated @RequestBody Blog blog) {
        System.out.println("编辑测试11111111111111111");
        System.out.println(blog.toString());
        System.out.println("当前用户ID：" + ShiroUtil.getProfile().getId());
        System.out.println(blog.toString());
//        System.out.println("当前用户id：" + ShiroUtil.getSubjectID());

        //      如果博客id不为空，就是编辑
        if (blog.getId() != null) {
//            temp = blogService.getOne(blog.getId());
//            每一个用户只能编辑自己的文章
//            Assert.isTrue(temp.getUserId().equals(ShiroUtil.getProfile().getId()), "你没有权限编辑");
            blogService.update(blog);
        } else {
            blog.setUserId(ShiroUtil.getProfile().getId());
            blog.setCreated(LocalDateTime.now());
            blog.setStatus(1);
            blogService.save(blog);
        }
        return Result.success("操作成功");
    }

    /**
     * 根据博客ID删除博客
     * @param id
     * @return
     */
    @RequiresAuthentication
    @RequestMapping(value = "/blog/delete",method = RequestMethod.POST)
    public Result deleteBlog(long id){
        System.out.println(id);
        System.out.println("------------");
        blogService.delete(id);
        return Result.success(true);
    }

    /**
    * <desc>
    *      查询用户发表文章数
    * </desc>
    * @param userId
    * @return:
    * @author LiuYu
    * @date: 2021-10-22
     **/
    @RequiresAuthentication
    @PostMapping("/blog/BlogCount")
    public Result getBlogCount(Integer userId){
        Integer count = blogService.blogCount();
        System.out.println("count======================"+count);
        return Result.success(count);
    }

    /**
    * <desc>
    *     文章点赞   key : userId + "@" + blogId
    * </desc>
    * @param blogId
    * @param userId
    * @return: com.gyg.common.lang.Result
    * @author LiuYu
    * @date: 2021-10-25
     **/
    @RequiresAuthentication
    @PostMapping("/blog/like")
    public Result like(Integer blogId,Integer userId){
        Integer like = 0;
        System.out.println("blogId==============="+blogId);
        redisUtil.set(userId + "@" + blogId, "true");
        like = Integer.parseInt(redisUtil.get("@" + blogId));
        like++;
        redisUtil.set("@" + blogId, "" + like);
        return Result.success(like);
    }

    /**
     * <desc>
     *     取消文章 点赞
     * </desc>
     * @param blogId
     * @param userId
     * @return: com.gyg.common.lang.Result
     * @author LiuYu
     * @date: 2021-10-25
     **/
    @RequiresAuthentication
    @PostMapping("/blog/unlike")
    public Result unlike(Integer blogId,Integer userId){
        Integer like = 0;
        System.out.println("blogId==============="+blogId);
        like = Integer.parseInt(redisUtil.get("@"+blogId));
        like--;
        redisUtil.set("@"+blogId,""+like);
        redisUtil.del(userId+"@"+blogId);
        if(like <0){
            return Result.fail("错误");
        }
        return Result.success(like);
    }

    /**
    * <desc>
    *      文章点赞数 key : "@"+blogId
    * </desc>
    * @param blogId
    * @return: com.gyg.common.lang.Result
    * @author LiuYu
    * @date: 2021-10-26
     **/
    @RequiresAuthentication
    @PostMapping("/blog/likeCount")
    public Result likeCount(Integer blogId){
        Integer like = 0;
        System.out.println("blogId==============="+blogId);
        like = Integer.parseInt(redisUtil.get("@"+blogId));
        if(like <0){
            return Result.fail("错误");
        }
        return Result.success(like);
    }

    /**
    * <desc>
    *     判断用户是否点赞、收藏、关注
    * </desc>
    * @param blogId
    * @param userId
    * @return: com.gyg.common.lang.Result
    * @author LiuYu
    * @date: 2021-10-25
     **/
    @RequiresAuthentication
    @PostMapping("/blog/islike")
    public Result isLike(Integer blogId,Integer userId){
        System.out.println("blogId==============="+blogId);
        System.out.println("userId==============="+userId);
        Map<String,Boolean> map = new HashMap<>();
        if(null == redisUtil.get(userId+"@"+blogId)){
            map.put("liked",false);
        }else {
            map.put("liked",true);
        }
        if(null == redisUtil.get(userId+"$"+blogId)){
            map.put("collected",false);
        }else {
            map.put("collected",true);
        }
        if(null == redisUtil.get(userId +"%"+1)){
            map.put("followed",false);
        }else {
            map.put("followed",true);
        }
        return Result.success(map);
    }

    /**
    * <desc>
    *      获取用户点赞数、收藏数
    * </desc>
    * @param userId
    * @return: com.gyg.common.lang.Result
    * @author LiuYu
    * @date: 2021-10-25
     **/
    @RequiresAuthentication
    @PostMapping("/blog/userLikeCount")
    public Result getUserLikeCount(Long userId){
        Map<String,Integer> result = new HashMap<>();
        Integer countLike=0,countCollect=0;
        Set<String> keySet = redisUtil.getKeys();
        List<Blog> blogs = blogService.list();
        //获取用户的文章
        for(Blog blog:blogs){
            for (String key:keySet){
                //获取用户文章的所有点赞数
                if(key.substring(0,1).equals("@")){
                    if(key.substring(1).equals(""+blog.getId())){
                        countLike += Integer.parseInt(redisUtil.get(key));
                    }
                }
                //获取用户文章的所有收藏数
                if(key.substring(0,1).equals("$")){
                    if(key.substring(1).equals(""+blog.getId())){
                        countCollect += Integer.parseInt(redisUtil.get(key));
                    }
                }
            }
        }
        result.put("countLike",countLike);
        result.put("countCollect",countCollect);
        return Result.success(result);
    }

    /**
    * <desc>
    *      文章收藏  key : userId + "$" + blogId
    * </desc>
    * @param blogId
    * @param userId
    * @return: com.gyg.common.lang.Result
    * @author LiuYu
    * @date: 2021-10-26
     **/
    @RequiresAuthentication
    @PostMapping("/blog/collect")
    public Result collect(Integer blogId,Integer userId){
        Integer collect = 0;
        System.out.println("blogId==============="+blogId);
        redisUtil.set(userId + "$" + blogId, "true");
        collect = Integer.parseInt(redisUtil.get("$" + blogId));
        collect++;
        redisUtil.set("$" + blogId, "" + collect);
        return Result.success(collect);
    }


    /**
    * <desc>
    *   取消文章点赞
    * </desc>
    * @param blogId
    * @param userId
    * @return: com.gyg.common.lang.Result
    * @author LiuYu
    * @date: 2021-10-26
     **/
    @RequiresAuthentication
    @PostMapping("/blog/cancelCollect")
    public Result cancelCollect(Integer blogId,Integer userId){
        Integer collect = 0;
        System.out.println("blogId==============="+blogId);
        collect = Integer.parseInt(redisUtil.get("$" + blogId));
        collect--;
        redisUtil.set("$"+blogId,""+collect);
        redisUtil.del(userId+"$"+blogId);
        if(collect <0){
            return Result.fail("错误");
        }
        return Result.success(collect);
    }

    /**
    * <desc>
    *   文章收藏数   key : "$"+blogId
    * </desc>
    * @param blogId
    * @return: com.gyg.common.lang.Result
    * @author LiuYu
    * @date: 2021-10-26
     **/
    @RequiresAuthentication
    @PostMapping("/blog/collectCount")
    public Result collectCount(Integer blogId){
        Integer collect = 0;
        System.out.println("blogId==============="+blogId);
        collect = Integer.parseInt(redisUtil.get("$"+blogId));
        if(collect <0){
            return Result.fail("错误");
        }
        return Result.success(collect);
    }


}
